package com.example.AIstudy.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.AIstudy.domain.User;
import com.example.AIstudy.exception.AIstudyException;
import com.example.AIstudy.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/users")
@Api(tags = "用户信息管理API")
public class UserController {
    @Autowired
    UserService userService;


    @GetMapping("/id/{id}")
    @ApiOperation("根据id获取用户信息")
//    @PreAuthorize("hasAnyAuthority(#id.toString())")
    public User getUserByID(@ApiParam("用户ID")@PathVariable Integer id){
        //把密码字段清空 确保安全
        User user=userService.getUserByUserID(id);
        return user;
    }

    @GetMapping("/username/{username}")
    @ApiOperation("根据username获取用户信息")
//    @PreAuthorize("hasAnyAuthority('all', #username) ")
    public User getUserByUserName(@ApiParam("账户名") @PathVariable String username){
        User user=userService.getUserByUserName(username);
        return user;
    }

    @PostMapping("")
    @ApiOperation("新增一条用户记录")
    public User InsertUser(@ApiParam("用户信息")@RequestBody User user) throws AIstudyException {
        userService.insertUser(user);
        return user;
    }

    @PutMapping("")
    @ApiOperation("修改一条用户记录")
//    @PreAuthorize("hasAnyAuthority(#user.id.toString())")
    public void updateUser(@ApiParam("用户信息")@RequestBody User user) throws AIstudyException {
//        User user1=userService.getUserByOpenID(user.getOpenid());
//        if(user1!=null&&user1.getId()!=user.getId()){
//            throw new AIstudyException(AIstudyException.ErrorType.UPDATE_ERROR,"账号名已经存在，用户信息修改失败");
//        }
        userService.updateUserByID(user);
    }

    //根据条件查询用户，条件可以为空
    @ApiOperation("根据条件查询用户")
    @GetMapping("")
//    @PreAuthorize("hasAnyAuthority('all')")
    public IPage<User> findUser(@ApiParam("用户名称")@RequestParam(value = "username",required = false) String username,
                                @ApiParam("页码")@RequestParam(defaultValue = "0")Integer pageNum,
                                @ApiParam("每页记录数") @RequestParam(defaultValue = "10")Integer pageSize){
        Map<String,Object> condition=new HashMap<>();
        if(username!=null) {
            condition.put("username",username);
        }
        IPage<User> iPage=userService.findUsers(condition, pageNum,pageSize);
        return iPage;
    }
}
